<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from "vue";
import * as echarts from "echarts";
import type { ECharts, EChartsOption } from "echarts";
import { BarChartData, Formatter, AxisLabelConfig } from "@/types/charts";

const props = defineProps<{
  chartData: BarChartData;
  formatter?: Formatter;
}>();

//dom容器引用
const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: ECharts | null = null;

//init
const initChart = () => {
  if (!chartRef.value) return;
  //clear instance
  if (chartInstance) {
    chartInstance.dispose();
  }
  //new chart
  chartInstance = echarts.init(chartRef.value);
  // formatter options
  const axisLabelConfig: AxisLabelConfig = {
    interval: 0,
  };
  if (props.formatter !== undefined) {
    axisLabelConfig.formatter = props.formatter;
  }
  //options
  const options: EChartsOption = {
    title: {
      text: props.chartData.title,
      left: "center",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" },
    },
    xAxis: {
      type: "category",
      data: props.chartData.xAxisData,
      axisLabel: axisLabelConfig,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        type: "bar",
        data: props.chartData.seriesData,
      },
    ],
  };
  chartInstance.setOption(options);
};

//自动调整尺寸
const handleResize = () => {
  chartInstance?.resize();
};

onMounted(() => {
  initChart();
  window.addEventListener("resize", handleResize);
});

//监听数据，重新渲染
watch(
  () => props.chartData,
  () => {
    initChart();
  },
  { deep: true, immediate: true }
);

onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  chartInstance?.dispose();
  chartInstance = null;
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 400px;
  min-width: 200px;
}
</style>
